import 'dart:io';

import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:jar_replacer/theme_controller.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:intl/intl.dart'; // 如果需要格式化日期时间


class About extends StatefulWidget {
  const About({super.key});

  @override
  State<StatefulWidget> createState() {
    return _AboutState();
  }
}

class _AboutState extends State<About> {
  // 版本信息
  String version = '';
  // 构建号
  String buildNumber = '';
  String author = '墨璃';
  String osTime = '';
  String totalMemory = '';
  // Windows 11 Pro
  String productName = '';
  // 计算机名称
  String computerName = '';
  // Cpu Core
  int numberOfCores = 0;
  String availableMemory = '';
  String gpuDescription = '';
  String cpuInfo = '';
  String timeZoneStandardName = '';
  // java版本
  String javaVersion = '';
  // 判断java环境是否安装正常
  bool javaEnvInstall = true;
  static final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
  PackageInfo _packageInfo = PackageInfo(
    appName: 'Unknown',
    packageName: 'Unknown',
    version: 'Unknown',
    buildNumber: 'Unknown',
    buildSignature: 'Unknown',
    installerStore: 'Unknown',
  );

  @override
  void initState() {
    super.initState();
    // 初始化系统信息
    _initializeSystemInfo();
  }

  Future<void> initPlatformState() async {
    var deviceData = <String, dynamic>{};

    try {
      if (kIsWeb) {
        deviceData = _readWebBrowserInfo(await deviceInfoPlugin.webBrowserInfo);
      } else {
        deviceData = switch (defaultTargetPlatform) {
          TargetPlatform.android =>
              _readAndroidBuildData(await deviceInfoPlugin.androidInfo),
          TargetPlatform.iOS =>
              _readIosDeviceInfo(await deviceInfoPlugin.iosInfo),
          TargetPlatform.linux =>
              _readLinuxDeviceInfo(await deviceInfoPlugin.linuxInfo),
          TargetPlatform.windows =>
              _readWindowsDeviceInfo(await deviceInfoPlugin.windowsInfo),
          TargetPlatform.macOS =>
              _readMacOsDeviceInfo(await deviceInfoPlugin.macOsInfo),
          TargetPlatform.fuchsia => <String, dynamic>{
            'Error:': 'Fuchsia platform isn\'t supported'
          },
        };
      }
    } on PlatformException {
      deviceData = <String, dynamic>{
        'Error:': 'Failed to get platform version.'
      };
    }

    //
    setState(() {
      productName = deviceData["productName"] ?? "";
      computerName = deviceData["computerName"] ?? "";
      numberOfCores = deviceData["numberOfCores"];
      totalMemory = '${deviceData["systemMemoryInMegabytes"]/1024}G';
      javaVersion = deviceData["deviceId"]?.toString().replaceFirst("{", "").replaceFirst("}", "") ?? "";
    });
  }

  Future<String?> getJavaVersion() async {
    try {
      final result = await Process.run('java', ['-version']);
      // java -version 输出会写入标准错误流
      if (result.stderr.isNotEmpty) {
        // 解析 stderr 中的版本信息
        final lines = result.stderr.split('\n');
        for (var line in lines) {
          if (line.contains('version')) {
            final parts = line.split('"');
            if (parts.length > 1) {
              String javaVersionEnv = parts[1];
              setState(() {
                javaVersion = javaVersionEnv;
              });
              return javaVersionEnv; // 返回版本号部分
            }
          }
        }
      }
    } catch (e) {
      print("Failed to get Java version: $e");
      setState(() {
        javaEnvInstall = false;
      });
    }

    return null;
  }

  final DateFormat formatter = DateFormat('yyyy年MM月dd日HH:mm:ss');

  Future<void> _initializeSystemInfo() async {
    // 获取当前操作系统时间
    final now = DateTime.now();
    setState(() {
      osTime = formatter.format(now);
      timeZoneStandardName = now.timeZoneName;
    });
    // 获取java版本
    getJavaVersion();

    final info = await PackageInfo.fromPlatform();
    setState(() {
      _packageInfo = info;
    });

    // 获取获取平台状态
    initPlatformState();
  }

  Map<String, dynamic> _readAndroidBuildData(AndroidDeviceInfo build) {
    return <String, dynamic>{
      'version.securityPatch': build.version.securityPatch,
      'version.sdkInt': build.version.sdkInt,
      'version.release': build.version.release,
      'version.previewSdkInt': build.version.previewSdkInt,
      'version.incremental': build.version.incremental,
      'version.codename': build.version.codename,
      'version.baseOS': build.version.baseOS,
      'board': build.board,
      'bootloader': build.bootloader,
      'brand': build.brand,
      'device': build.device,
      'display': build.display,
      'fingerprint': build.fingerprint,
      'hardware': build.hardware,
      'host': build.host,
      'id': build.id,
      'manufacturer': build.manufacturer,
      'model': build.model,
      'product': build.product,
      'supported32BitAbis': build.supported32BitAbis,
      'supported64BitAbis': build.supported64BitAbis,
      'supportedAbis': build.supportedAbis,
      'tags': build.tags,
      'type': build.type,
      'isPhysicalDevice': build.isPhysicalDevice,
      'systemFeatures': build.systemFeatures,
      'serialNumber': '...',
      'isLowRamDevice': build.isLowRamDevice,
    };
  }

  Map<String, dynamic> _readIosDeviceInfo(IosDeviceInfo data) {
    return <String, dynamic>{
      'name': data.name,
      'systemName': data.systemName,
      'systemVersion': data.systemVersion,
      'model': data.model,
      'localizedModel': data.localizedModel,
      'identifierForVendor': data.identifierForVendor,
      'isPhysicalDevice': data.isPhysicalDevice,
      'utsname.sysname:': data.utsname.sysname,
      'utsname.nodename:': data.utsname.nodename,
      'utsname.release:': data.utsname.release,
      'utsname.version:': data.utsname.version,
      'utsname.machine:': data.utsname.machine,
    };
  }

  Map<String, dynamic> _readLinuxDeviceInfo(LinuxDeviceInfo data) {
    return <String, dynamic>{
      'name': data.name,
      'version': data.version,
      'id': data.id,
      'idLike': data.idLike,
      'versionCodename': data.versionCodename,
      'versionId': data.versionId,
      'prettyName': data.prettyName,
      'buildId': data.buildId,
      'variant': data.variant,
      'variantId': data.variantId,
      'machineId': data.machineId,
    };
  }

  Map<String, dynamic> _readWebBrowserInfo(WebBrowserInfo data) {
    return <String, dynamic>{
      'browserName': data.browserName.name,
      'appCodeName': data.appCodeName,
      'appName': data.appName,
      'appVersion': data.appVersion,
      'deviceMemory': data.deviceMemory,
      'language': data.language,
      'languages': data.languages,
      'platform': data.platform,
      'product': data.product,
      'productSub': data.productSub,
      'userAgent': data.userAgent,
      'vendor': data.vendor,
      'vendorSub': data.vendorSub,
      'hardwareConcurrency': data.hardwareConcurrency,
      'maxTouchPoints': data.maxTouchPoints,
    };
  }

  Map<String, dynamic> _readMacOsDeviceInfo(MacOsDeviceInfo data) {
    return <String, dynamic>{
      'computerName': data.computerName,
      'hostName': data.hostName,
      'arch': data.arch,
      'model': data.model,
      'kernelVersion': data.kernelVersion,
      'majorVersion': data.majorVersion,
      'minorVersion': data.minorVersion,
      'patchVersion': data.patchVersion,
      'osRelease': data.osRelease,
      'activeCPUs': data.activeCPUs,
      'memorySize': data.memorySize,
      'cpuFrequency': data.cpuFrequency,
      'systemGUID': data.systemGUID,
    };
  }

  Map<String, dynamic> _readWindowsDeviceInfo(WindowsDeviceInfo data) {
    //

    return <String, dynamic>{
      'numberOfCores': data.numberOfCores,
      'computerName': data.computerName,
      'systemMemoryInMegabytes': data.systemMemoryInMegabytes,
      'userName': data.userName,
      'majorVersion': data.majorVersion,
      'minorVersion': data.minorVersion,
      'buildNumber': data.buildNumber,
      'platformId': data.platformId,
      'csdVersion': data.csdVersion,
      'servicePackMajor': data.servicePackMajor,
      'servicePackMinor': data.servicePackMinor,
      'suitMask': data.suitMask,
      'productType': data.productType,
      'reserved': data.reserved,
      'buildLab': data.buildLab,
      'buildLabEx': data.buildLabEx,
      'digitalProductId': data.digitalProductId,
      'displayVersion': data.displayVersion,
      'editionId': data.editionId,
      'installDate': data.installDate,
      'productId': data.productId,
      'productName': data.productName,
      'registeredOwner': data.registeredOwner,
      'releaseId': data.releaseId,
      'deviceId': data.deviceId,
    };
  }

  @override
  Widget build(BuildContext context) {
    final themeController = Get.find<ThemeController>();
    return Acrylic(
          // 设置应用于 Acrylic 效果的颜色。这个颜色会与底层内容混合。
          tint: Colors.white.withOpacity(0.1),
          //tintAlpha: 0.5,
          // 设置模糊的程度，数值越大，模糊效果越强。
          blurAmount: 0.0, // 设置模糊程度
          // 阴影效果
          elevation: 0,
          child: Container(
              color: themeController.isDark
                  ? Colors.black.withOpacity(0.8)
                  : Colors.white,
              child: Padding(
                padding: EdgeInsets.all(16.0), // 减少外边距以适应更多内容
                child: Padding(
                  padding: EdgeInsets.all(20),
                  child: Column(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    // 居中对齐所有子组件
                    children: [
                    const Card(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          CircleAvatar(
                            radius: 50,
                            backgroundImage:
                                AssetImage('assets/images/avatar.jpg'),
                          )
                        ],
                      ),
                    ),

                    Card(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text("版本", style: TextStyle(color: themeController.isDark?Colors.white:Colors.black)),
                          Text(
                            "BootJar Replacer 2024.12.7, ${_packageInfo.version} Build ${_packageInfo.buildNumber}",
                            style: TextStyle(fontSize: 16, color: themeController.isDark?Colors.white:Colors.black),
                          ),
                        ],
                      ),
                    ),
                    Card(
                        child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text('作者 ', style: TextStyle(fontSize: 16, color: themeController.isDark?Colors.white:Colors.black)),
                        Text('墨璃', style: TextStyle(fontSize: 16, color: themeController.isDark?Colors.white:Colors.black))
                      ],
                    )),
                    Card(
                        child: Row(
                      children: [
                        Text("构建信息", style: TextStyle(color: themeController.isDark?Colors.white:Colors.black)),
                        Text(
                            "Build 22621.1.amd64fre.ni_release.220506-1250, built on December 7, 2024", style: TextStyle(color: themeController.isDark?Colors.white:Colors.black)),
                      ],
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    )),
                    Card(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text('gitee', style: TextStyle(fontSize: 16, color: themeController.isDark?Colors.white:Colors.black)),
                          GestureDetector(
                            onTap: () => launchUrl(Uri.parse(
                                'https://gitee.com/mchangtian/jar_replacer')),
                            child: Padding(
                              padding: EdgeInsets.symmetric(vertical: 8.0),
                              child: Text(
                                'https://gitee.com/mchangtian/jar_replacer',
                                style: TextStyle(
                                  color: Colors.blue,
                                  decoration: TextDecoration.none,
                                  fontSize: 16,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),

                    // 链接部分
                    Card(
                        child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("操作系统", style: TextStyle(color: themeController.isDark?Colors.white:Colors.black)),
                        Text(productName, style: TextStyle(color: themeController.isDark?Colors.white:Colors.black)),
                      ],
                    )),
                    Card(
                        child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("内存", style: TextStyle(color: themeController.isDark?Colors.white:Colors.black)),
                        Text(totalMemory, style: TextStyle(color: themeController.isDark?Colors.white:Colors.black)),
                      ],
                    )),
                    Card(
                        child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("CPU Core", style: TextStyle(color: themeController.isDark?Colors.white:Colors.black)),
                        Text('$numberOfCores', style: TextStyle(color: themeController.isDark?Colors.white:Colors.black)),
                      ],
                    )),
                    Card(
                        child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("java版本", style: TextStyle(color: themeController.isDark?Colors.white:Colors.black)),
                        Text(javaEnvInstall?javaVersion:"java环境检测异常", style: TextStyle(color: javaEnvInstall?(themeController.isDark?Colors.white:Colors.black):Colors.red),),
                      ],
                    )),
                    Card(
                        child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("当前时区", style: TextStyle(color: themeController.isDark?Colors.white:Colors.black)),
                        Text(timeZoneStandardName, style: TextStyle(color: themeController.isDark?Colors.white:Colors.black)),
                      ],
                    )),
                    Card(
                        child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("系统时间", style: TextStyle(color: themeController.isDark?Colors.white:Colors.black)),
                        Text(osTime, style: TextStyle(color: themeController.isDark?Colors.white:Colors.black)),
                      ],
                    )),
                    Card(
                        child: Row(
                      children: [
                        Text('简介:', style: TextStyle(fontSize: 16, color: themeController.isDark?Colors.white:Colors.black)),
                        SizedBox(
                          width: 10,
                        ),
                        Expanded(
                            child: Text(
                          '本应用程序是一款专为 Java 开发者设计的实用工具，旨在简化 Spring Boot 项目的 JAR 文件替换和重新打包过程。通过图形化界面，用户可以轻松地替换项目中的特定 JAR 文件，并生成一个新的、可运行的 Spring Boot 应用程序包。',
                          style: TextStyle(color: themeController.isDark?Colors.white:Colors.black),
                        ))
                      ],
                    ))
                  ],
                ),
              ),
            )));
  }
}
